package hn.cch.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MathUtil {


    private static final Logger logger = LoggerFactory.getLogger(MathUtil.class);

    /**
     * 相关系数
     * correlation coefficient
     *
     * @return
     */
    public double r(double[] X, double[] Y) {
        double covXY = cov(X, Y);
        double varX = var(X);
        double varY = var(Y);
        // 计算相关系数
        return covXY / Math.sqrt(varX * varY);
    }


    /**
     * 协方差covariance
     *
     * @param X
     * @param Y
     * @return
     */
    public double cov(double[] X, double[] Y) {
        if (X.length != Y.length) {
            return 0;
        }

        int len = X.length;
        double[] XY = new double[9];
        for (int i = 0; i < len; i++) {
            XY[i] = X[i] * Y[i];
        }

        double meanX = mean(X);
        double meanY = mean(Y);
        double meanXY = mean(XY);

        double result = 0;
        result = meanXY - meanX * meanY;
        return result;
    }

    /**
     * 方差variance
     *
     * @param doubles
     * @return
     */
    public double var(double[] doubles) {

        double mean = mean(doubles);
        int len = doubles.length;
        double result = 0;
        double temp = 0;
        for (int i = 0; i < len; i++) {
            temp = doubles[i] - mean;
            result += temp * temp;
        }
        result = result / len;
        return result;
    }


    /**
     * 求平均值
     *
     * @param doubles
     * @return
     */
    public double mean(double[] doubles) {
        double sum = sum(doubles);
        int len = doubles.length;
        double result = sum / len;
        return result;
    }

    /**
     * 求和
     *
     * @param doubles
     * @return
     */
    public double sum(double[] doubles) {
        double result = 0;
        for (int i = 0; i < doubles.length; i++) {
            result += doubles[i];
        }
        return result;
    }
}
